<template>
  <div style="display: flex">
    <div class="chat-container">
      <h1>游戏策划AI小助手</h1>
      <!-- 消息列表 -->
      <div class="message-list">
        <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
          <div class="avatar">{{ msg.role === 'user' ? '👤' : '🤖' }}</div>
          <div class="bubble">{{ msg.text }}</div>
        </div>
        <div v-if="isTyping" class="message ai">
          <div class="avatar">🤖</div>
          <div class="bubble typing">{{ currentAIText }}<span class="cursor">|</span></div>
        </div>
      </div>

      <!-- 输入框 -->
      <div class="input-area">
        <input
            v-model="userInput"
            @keyup.enter="sendMessage"
            placeholder="输入消息..."
            :disabled="isWaitingResponse"
        />
        <button @click="sendMessage" :disabled="isWaitingResponse">发送</button>
      </div>
    </div>
    <div style="flex: 3">
      <iframe
          src="https://map.zq12369.com/"
          class="iframe-container"
          frameborder="0"
          allow="geolocation"
          allowfullscreen>
      </iframe>
    </div>
  </div>

</template>

<script>
export default {
  data() {
    return {
      messages: [],
      userInput: "",
      currentAIText: "",
      isTyping: false,
      isWaitingResponse: false,
      typingSpeed: 20,
      typingTimer: null,
      abortController: null // 用于取消请求
    };
  },
  methods: {
    async sendMessage() {
      if (!this.userInput.trim() || this.isWaitingResponse) return;

      // 1. 添加用户消息
      this.messages.push({
        role: "user",
        text: this.userInput
      });
      const userMessage = this.userInput;
      this.userInput = "";
      this.isWaitingResponse = true;

      // 2. 创建AbortController以便取消请求
      this.abortController = new AbortController();

      try {
        const response = await fetch("/youxich/agent/answer", {
          method: "POST",
          headers: {"Content-Type": "application/json"},
          body: JSON.stringify({message: userMessage}),
          signal: this.abortController.signal
        });

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        if (!response.body) {
          throw new Error("ReadableStream not supported in this browser");
        }

        // 3. 处理流式响应
        const reader = response.body.getReader();
        const decoder = new TextDecoder("utf-8");
        let fullText = "";
        let buffer = "";

        while (true) {
          const {done, value} = await reader.read();
          if (done) break;

          buffer += decoder.decode(value, {stream: true});

          // 处理可能的多行数据
          const lines = buffer.split(/\r\n|\n|\r/);
          buffer = lines.pop() || ""; // 保存未完成的行

          for (const line of lines) {
            if (line.startsWith('data:')) {
              try {
                const jsonStr = line.substring(5).trim();
                if (jsonStr) {
                  const data = JSON.parse(jsonStr);
                  const newText = this.extractAIText(data);
                  if (newText) {
                    fullText += newText;
                    this.playTypingEffect(newText);
                  }
                }
              } catch (err) {
                console.error('解析错误:', err);
              }
            }
          }
        }

        // 4. 处理剩余缓冲数据
        if (buffer.trim()) {
          try {
            const data = JSON.parse(buffer.substring(5).trim());
            const newText = this.extractAIText(data);
            if (newText) {
              fullText += newText;
              this.playTypingEffect(newText);
            }
          } catch (err) {
            console.error('最终解析错误:', err);
          }
        }

        // 5. 最终添加到消息列表
        this.messages.push({
          role: "ai",
          text: fullText
        });

      } catch (err) {
        if (err.name === 'AbortError') {
          console.log('请求已被取消');
        } else {
          console.error("请求失败:", err);
          this.messages.push({
            role: "ai",
            text: "抱歉，AI暂时无法响应，请稍后再试。"
          });
        }
      } finally {
        this.isWaitingResponse = false;
        this.isTyping = false;
        this.currentAIText = "";
        clearInterval(this.typingTimer);
        this.abortController = null;
      }
    },

    // 取消请求的方法
    cancelRequest() {
      if (this.abortController) {
        this.abortController.abort();
      }
    },

    // 从API响应中提取AI文本
    extractAIText(data) {
      let result = "";
      if (data?.data?.message?.content) {
        data.data.message.content.forEach(item => {
          if (item.data?.text) {
            result += item.data.text;
          }
        });
      }
      return result;
    },

    // 打字机效果
    playTypingEffect(fullText) {
      this.isTyping = true;
      clearInterval(this.typingTimer);

      let i = 0;
      // this.currentAIText = "";
      this.typingTimer = setInterval(() => {
        if (i < fullText.length) {
          this.currentAIText += fullText.charAt(i);
          i++;
          // 自动滚动到底部
          this.$nextTick(() => {
            const container = this.$el.querySelector(".message-list");
            container.scrollTop = container.scrollHeight;
          });
        } else {
          clearInterval(this.typingTimer);
        }
      }, this.typingSpeed);
    }
  },
  beforeDestroy() {
    // 组件销毁时取消请求
    this.cancelRequest();
    clearInterval(this.typingTimer);
  }
};
</script>

<style scoped>
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 90vh;
  padding: 30px;
  border: 1px solid #ddd;
  background-image: linear-gradient(-225deg, #FFE29F 0%, #FFA99F 48%, #FF719A 100%);
  border-radius: 8px;
  overflow: hidden;
}

.message-list {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #f9f9f9;
}

.message {
  display: flex;
  margin-bottom: 12px;
}

.avatar {
  margin-right: 10px;
  font-size: 20px;
}

.bubble {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 18px;
  line-height: 1.4;
}

.user {
  justify-content: flex-end;
}

.user .bubble {
  background: #1890ff;
  color: white;
}

.ai {
  justify-content: flex-start;
}

.ai .bubble {
  background: white;
  border: 1px solid #eee;
}

.typing {
  position: relative;
}

.cursor {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0;
  }
}

.input-area {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ddd;
  background: white;
}

.input-area input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  outline: none;
}

.input-area button {
  margin-left: 8px;
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

.iframe-container {
  width: 100%;
  height: 100vh;
  border: none;
}
</style>